package cn.uestc.labhms.modules.hms.controller;

import cn.uestc.labhms.common.annotation.SysLog;
import cn.uestc.labhms.common.utils.R;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author Mu.tz
 */
@Slf4j
@RestController
public class SysManageController {
    @Value("${hms.file.download.path}")
    private String downloadFile;
    @GetMapping(value = "/get/file/model")
    public String download(HttpServletResponse response) {
        File file = new File(downloadFile);
        if(!file.exists()){
            return "下载文件不存在";
        }
        response.reset();
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setContentLength((int) file.length());
        String fileName = FilenameUtils.getName(downloadFile);
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

        try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));) {
            byte[] buff = new byte[1024];
            OutputStream os  = response.getOutputStream();
            int i = 0;
            while ((i = bis.read(buff)) != -1) {
                os.write(buff, 0, i);
                os.flush();
            }
        } catch (IOException e) {
            log.error("{}",e);
            return "下载失败";
        }
        log.info("下载文件成功");
        return "下载成功";
    }
}
